//
//  SGJHomeController.m
//  Sewage
//
//  Created by 宗庆猛 on 2017/5/26.
//  Copyright © 2017年 宗庆猛. All rights reserved.
//

#import "SGJHomeController.h"

#import <SDCycleScrollView.h>

#import "SGJNetworkTools.h"

#import <YYModel.h>
#import "SGJBannerModel.h"
#import "SGJGrabOrderModel.h"

#import <AMapLocationKit/AMapLocationKit.h>
#import "SGJGrabOrderCell.h"
#import "SGJUserModel.h"

#import "SGJTaskDetailViewController.h"

#import "CustomalertViewController.h"

static  NSString *DOMAIN_URL_PIC=@"http://oowmepah0.bkt.clouddn.com/";


@interface SGJHomeController ()<AMapLocationManagerDelegate,UITableViewDelegate,UITableViewDataSource,SGJGrabOrderCellDelegate>

@property (strong,nonatomic) AMapLocationManager *locationManager;

@property (strong,nonatomic) SDCycleScrollView *cycleScrollView;

@property (strong,nonatomic) NSArray *bannerArray;

@property (strong,nonatomic) UITableView *tableView;

@property (strong,nonatomic) NSArray *grabOrderList;


@property (nonatomic,strong) UIView *cvtt_nothingView;//可通用的部分。cvtt_前缀

@end

@implementation SGJHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGRect frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 180);
    
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    
    //self.locationManager.distanceFilter ＝ 200;
    
    // 带逆地理信息的一次定位（返回坐标和地址信息）
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    
    [self loadData];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    
    // 网络加载图片的轮播器
   // __weak typeof (self) WSelf = self;
    SDCycleScrollView *cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:frame delegate:self placeholderImage:nil];
    
    [cycleScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBanner)]];

    //[self.view addSubview:cycleScrollView];
    self.cycleScrollView = cycleScrollView;
  
    UITableView *tableView = [[UITableView alloc] init];
    tableView.frame = CGRectMake(0, -20, frame.size.width, [UIScreen mainScreen].bounds.size.height + 20);
    tableView.backgroundColor = [UIColor lightGrayColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.tableHeaderView = cycleScrollView;
    //[tableView registerClass:[SGJGrabOrderCell class] forCellReuseIdentifier:@"grabOrder"];
    [tableView registerNib:[UINib nibWithNibName:@"SGJGrabOrderCell" bundle:nil] forCellReuseIdentifier:@"grabOrder"];
    [self.view addSubview:tableView];
    self.tableView = tableView;
}

-(void)tapBanner{

    
}

// 设置去掉navigationBar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    self.navigationController.navigationBarHidden = YES;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.navigationController.toolbarHidden = YES;
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.grabOrderList.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SGJGrabOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"grabOrder" forIndexPath:indexPath];
    cell.grabOrderModel = self.grabOrderList[indexPath.row];
    // Configure the cell...
    
    cell.delegate = self;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 180;
}

#pragma mark - SGJGrabOrderCellDelegate
-(void)checkDetailWithGrabOrderCell:(SGJGrabOrderCell *)grabOrderCell{
    NSLog(@"点击了查看详情%@",grabOrderCell);
    
    SGJTaskDetailViewController *taskDetailVc = [[SGJTaskDetailViewController alloc] init];
    taskDetailVc.grabOrderModel = grabOrderCell.grabOrderModel;
    [self.navigationController pushViewController:taskDetailVc animated:YES];
}

-(void)grabOrderWithGrabOrderCell:(SGJGrabOrderCell *)grabOrderCell{
    NSLog(@"点击了立即抢单%@",grabOrderCell);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];

    param[@"taskId"] = grabOrderCell.grabOrderModel.id;
    
    [[SGJNetworkTools sharedNetworkTool] grabOrderWithUrlString:kGrabTaskUrl parameters:param method:@"POST" callBack:^(id responseObject) {
        CustomalertViewController * alertVC =[CustomalertViewController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@",responseObject[@"retData"] ] withSureButtonTitle:@"知道了" withSureCancellTitle:nil preferredStyle:UIAlertControllerStyleAlert handler:^(UIAlertAction *action)
                                              {
                                              }];
        [self presentViewController:alertVC animated:YES completion:nil];
    }];
    
}


-(void)loadData{
    
    // 带逆地理（返回坐标和地址信息）。将下面代码中的 YES 改成 NO ，则不会返回地址信息。
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
            
            if (error.code == AMapLocationErrorLocateFailed)
            {
                return;
            }
        }
        
        NSLog(@"location:%@", location);
        
        if (regeocode)
        {
            NSLog(@"reGeocode:%@   adcode:%@", regeocode,regeocode.adcode);
            
            [self getBannerDataWithAdcode:regeocode.adcode];
            
            [self getGrabOrderListWith:regeocode];
        }
    }];

    
}
-(void)getBannerDataWithAdcode:(NSString *)adcode{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    //[String areaCode:县级行政区编码] 或者([String province:省名称],[String city:市名称],[String county:乡镇名称])
    param[@"areaCode"] = adcode;
    SGJNetworkTools *netTools = [SGJNetworkTools sharedNetworkTool];
    //netTools.responseSerializer = [AFHTTPResponseSerializer serializer];
    [netTools loadHomeBannerWithUrlString:kGetBannerUrl parameters:param method:@"POST" callBack:^(id responseObject) {
        NSLog(@"banner数据%@",responseObject);
        
        if ([responseObject[@"retCode"] integerValue] == 0) {
            
            self.bannerArray = [NSArray yy_modelArrayWithClass:[SGJBannerModel class] json:responseObject[@"retData"]];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            [self.bannerArray enumerateObjectsUsingBlock:^(SGJBannerModel  * obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *imageUrl = [NSString stringWithFormat:@"%@%@",DOMAIN_URL_PIC,obj.img];
                [tempArray addObject:imageUrl];
            }];
            
            self.cycleScrollView.imageURLStringsGroup = tempArray;//是否需要放在主线程？ 是否需要刷新
        }
    }];

    
}

-(void)getGrabOrderListWith:(AMapLocationReGeocode *)regeocode{
    //加载home list
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    //{areaCode:111,province:陕西省,city:西安市,county:高新区,taskId:11111}
    //真机
    param[@"areaCode"]= regeocode.adcode;
    param[@"province"]= regeocode.province;
    param[@"city"]= regeocode.city;
    param[@"county"]= regeocode.country;
    //模拟器---真机需要注释掉一下部分
    param[@"areaCode"]= @"610113";
    param[@"province"]= @"陕西省";
    param[@"city"]= @"西安市";
    param[@"county"]= @"雁塔区";
    param[@"taskId"]= @"";
    
    param[@"userId"]= [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    [[SGJNetworkTools sharedNetworkTool] loadHomeGrapOrderWithUrlString:kGetHomeGrabOrdersUrl parameters:param method:@"POST" callBack:^(id responseObject) {
        NSLog(@"抢单list%@",responseObject);
        
        if ([responseObject[@"retCode"] integerValue] == 0) {
            NSArray *tempArray = [NSArray yy_modelArrayWithClass:[SGJGrabOrderModel class] json:responseObject[@"retData"]];
            
            self.grabOrderList = tempArray;
            
            [self.tableView reloadData];
        }
    }];

}

-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}




@end
